// Learn TypeScript:
//  - https://docs.cocos.com/creator/manual/en/scripting/typescript.html
// Learn Attribute:
//  - https://docs.cocos.com/creator/manual/en/scripting/reference/attributes.html
// Learn life-cycle callbacks:
//  - https://docs.cocos.com/creator/manual/en/scripting/life-cycle-callbacks.html

import { game } from "../../../../script/game/control/game";
import { ItemBase } from "../../../../script/game/control/Item/ItemBase";
import { itemType } from "../../../../script/game/gameType";
import { ccs } from "../../../../script/util/services";
import { WinBase } from "../../../../script/wins/WinBase";

const {ccclass, property} = cc._decorator;

@ccclass
export default class NewClass extends WinBase {

    @property(cc.Label)
    label: cc.Label = null;
    item: itemType;
    count: number = 1;
    cost: number = 0;
    start () {
        this.item = ccs.dataMgr.getItemsById(this._args.id);
        this.nodes.itemName.getComponent(cc.Label).string = this.item.name;
        this.nodes.stock.getComponent(cc.Label).string = "已拥有：" + game.playerMgr.bag.itemsBag.getItemCount(this._args.id).toString(); //库存
        this.cost = this.count * this.item.price;
        this.nodes.cost.getComponent(cc.Label).string = "总价：" + this.cost + "元";
        this.touchEndEventScale(this.nodes.reduce, () => {
            this.count -= 1;
            this.limitCount();
        })
        this.touchEndEventScale(this.nodes.add, () => {
            this.count += 1;
            this.limitCount();
        })
        this.touchEndEventScale(this.nodes.ensure, () => {
            this.buy();
        })
    }
    limitCount() {
        if(this.count < 1) {
            this.count = 1;
        }else if(this.count > 1000) {
            this.count = 1000;
        }
        this.nodes.count.getComponent(cc.Label).string = this.count.toString();
        this.cost = Math.ceil(this.count * this.item.price);
        this.nodes.cost.getComponent(cc.Label).string = "总价：" + this.cost + "元";
    }
    onSlider(tar, i) {
        let num = tar.progress;
        let tmp = Math.ceil(num * 1000);
        this.count = tmp;
        this.limitCount();
    }
    buy() {
        //查看钱
        if(game.playerMgr.heroInfo.money >= this.cost ) {
            game.playerMgr.heroInfo.money -= this.cost;
            game.playerMgr.bag.itemsBag.addItem(new ItemBase(this.item, this.count));
            ccs.winMgr.showWin("toast", { msg: "购买成功" });
            this._close();
        } else {
            ccs.winMgr.showWin("toast", { msg: "钱包有点羞涩" });
            
        }
        cc.log(game.playerMgr.bag.itemsBag);
    }
}
